package com.ruoyi.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.basedocument.domain.*;
import com.ruoyi.basedocument.mapper.BomCostcenterMapper;
import com.ruoyi.basedocument.mapper.BomRawmaterialMapper;
import com.ruoyi.basedocument.mapper.BomSpecialmaterialMapper;
import com.ruoyi.basedocument.service.*;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import com.ruoyi.task.mapper.BomBaseDataTaskUtilMapper;
import com.ruoyi.util.HubUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 定时同步基础资料
 */
@Component("BomBaseDataTask")
public class BomBaseDataTask {

    private final static Logger logger = LoggerFactory.getLogger(BomBaseDataTask.class);

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private BomBaseDataTaskUtilMapper omsBaseDataTaskUtilMapper;

    @Autowired
    private IBomSpecialmaterialService bomSpecialmaterialService;
    @Autowired
    private BomSpecialmaterialMapper bomSpecialmaterialMapper;

    @Autowired
    private IBomRawmaterialService bomRawmaterialService;
    @Autowired
    private BomRawmaterialMapper bomRawmaterialMapper;

    @Autowired
    private IBomBaseunitService bomBaseunitService;

    @Autowired
    private IBomCustomerService bomCustomerService;

    @Autowired
    private IBomCostcenterService bomCostcenterService;

    @Autowired
    private BomCostcenterMapper bomCostcenterMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private ISysDeptService sysDeptServiceImpl;

    @Autowired
    private IBomMaterialgroupService bomMaterialgroupService;

    @Autowired
    private IBomMaterialhalfService bomMaterialhalfService;

    @Autowired
    private IBomAsscategoryService bomAsscategoryService;

    public JSONObject loginEas() {
        try {
            System.out.println("--------------开始登录成本测算hub接口");
            SysConfig sysConfig = sysConfigService.selectConfigByConfigKey("loginurlbom");
            String s = HubUtil.doGetWithJson("" + sysConfig.getConfigValue() + sysConfig.getRemark());
            System.out.println("--------------成本测算hub登录接口：" + s);
            return JSON.parseObject(s);
//            System.out.println("--------------登录eas");
//            Service s = new Service();
//            Call call = (Call) s.createCall();
//            System.out.println("--------------创建Call对象");
//            call.setOperationName("login");
//            //此处URL地址根据调用服务器来指定
//            SysConfig sysConfig = sysConfigService.selectConfigByConfigKey("easLoginUrl");
//            String configValue = sysConfig.getConfigValue();
//            call.setTargetEndpointAddress(configValue);//facade发布路径
//            call.setReturnType(new QName("urn:client", "WSContext"));
//            call.setReturnClass(WSContextToBom.class);
//            call.setReturnQName(new QName("", "loginReturn"));
//            //超时
//            call.setTimeout(Integer.valueOf(1000 * 600000 * 60));
//            call.setMaintainSession(true);//登陆获取sessionid]
//            //登陆接口参数
//            //登陆接口参数说明：第一个参数:EAS登陆用户名,第二个参数:用户名密码,第三个参数:解决方案名称（通常为 eas）,第四个EAS数据中心编码可在EAS系统集成得到
//            WSContextToBom rs = (WSContextToBom) call.invoke(new Object[]{"user", "wfz123!!!", "eas", "wfz003", "l2", Integer.valueOf(0)});
//            return rs;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String getEasData(String method, String param) {
        try {
            Service s = new Service();
            Call call = (Call) s.createCall();
//            call.setTargetEndpointAddress("http://10.10.255.111:6888/ormrpc/services/WSMDMFacade?wsdl");//facade发布路径
            SysConfig sysConfig = sysConfigService.selectConfigByConfigKey("easGetData");
            String configValue = sysConfig.getConfigValue();
            call.setTargetEndpointAddress(configValue);//facade发布路径
            call.setReturnType(new QName("urn:lang.java", "String"));
            call.setOperationName(method);//方法名
            call.addParameter("requestMessage", XMLType.XSD_ANYTYPE, ParameterMode.IN);
            call.setTimeout(Integer.valueOf(1000 * 600000 * 60));
            String re = (String) call.invoke(new Object[]{param});
            return re;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取token信息
     */
    private JSONObject loginParam() {
        System.out.println("--------------开始登录结算中台hub接口");
        SysConfig sysConfig = sysConfigService.selectConfigByConfigKey("loginurl");
        String s = HubUtil.doGetWithJson("" + sysConfig.getConfigValue() + sysConfig.getRemark());
        System.out.println("--------------结算中台hub登录接口：" + s);
        return JSON.parseObject(s);
    }

    /**
     * 定时同步物料
     */
    public synchronized void SynMaterial() {
        JSONObject loginParam = loginParam();
        String access_token = (String) loginParam.get("access_token");
        String token_type = (String) loginParam.get("token_type");
        String expires_in = loginParam.get("expires_in").toString();
        SysConfig sysConfig = sysConfigService.selectConfigByConfigKey("materialUrl");
        String s1 = "";
        Date successData = omsBaseDataTaskUtilMapper.getSuccessData("BomBaseDataTask.SynMaterial");
        //判断该定时任务之前是否存在成功的调度日志，有的话获取时间
        if (!StringUtils.isNull(successData)) {
            //增量获取
            String format = new SimpleDateFormat("yyyy-MM-dd").format(successData);
            s1 = HubUtil.doGetWithJson(
                    sysConfig.getConfigValue() + sysConfig.getRemark() + "'" + format + "'"
                    , token_type, access_token);
        } else {
            //全量获取
            s1 = HubUtil.doPostWithJson(sysConfig.getConfigValue(), token_type, access_token);
        }
        logger.info("--------------增量同步物料时，获取的数据：" + s1);
        if (StringUtils.isBlank(s1)) {
            return;
        }
        JSONObject jsonObject = JSON.parseObject(s1);
        JSONArray data = jsonObject.getJSONArray("data");
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObject2 = data.getJSONObject(i);
            BomSpecialmaterial bdMaterial = new BomSpecialmaterial();
            BomBaseunit baseunit = new BomBaseunit();
            String materialnumber = jsonObject2.getString("materialnumber");
            if(StringUtils.isBlank(materialnumber)||"00".equals(materialnumber.substring(0,2))){
                continue;
            }
            bdMaterial.setMaterialnumber(materialnumber);
            bdMaterial.setMaterialname(jsonObject2.getString("materialname"));
            baseunit.setBaseunitnumber(jsonObject2.getString("baseunitnumber"));
            baseunit.setBaseunitname(jsonObject2.getString("baseunitname"));
            bdMaterial.setBaseunitnumber(jsonObject2.getString("baseunitnumber"));
            bdMaterial.setBaseunitname(jsonObject2.getString("baseunitname"));
            bdMaterial.setGroup1number(jsonObject2.getString("group1number"));
            bdMaterial.setGroup1name(jsonObject2.getString("group1name"));
            bdMaterial.setGroup2number(jsonObject2.getString("group2number"));
            bdMaterial.setGroup2name(jsonObject2.getString("group2name"));
            bdMaterial.setGroup3number(jsonObject2.getString("group3number"));
            bdMaterial.setGroup3name(jsonObject2.getString("group3name"));
            bdMaterial.setGroup4number(jsonObject2.getString("group4number"));
            bdMaterial.setGroup4name(jsonObject2.getString("group4name"));
            bdMaterial.setQtytoegg(jsonObject2.getString("qtytoegg"));
            bdMaterial.setQtytodumpling(jsonObject2.getString("qtytodumpling"));
            bdMaterial.setQtytocake(jsonObject2.getString("qtytocake"));
            bdMaterial.setBoxspecification(jsonObject2.getString("boxspecification"));
            bdMaterial.setIsspecialmaterial("0");
            bdMaterial.setTaxrate(jsonObject2.getBigDecimal("tax_rate"));
            bdMaterial.setCreatetime(jsonObject2.getDate("createtime"));
            bdMaterial.setUpdatetime(jsonObject2.getDate("write_date"));
            bdMaterial.setBarcode(jsonObject2.getString("barcode"));
            bdMaterial.setSpecifications(jsonObject2.getString("materialspecification"));
            bdMaterial.setSimplename(jsonObject2.getString("materialabbr"));
            BomSpecialmaterial tempMaterial = new BomSpecialmaterial();
            tempMaterial.setMaterialnumber(bdMaterial.getMaterialnumber());
            List<BomSpecialmaterial> bdMaterials = bomSpecialmaterialService.selectBomSpecialmaterialList2(tempMaterial);
            if (StringUtils.isEmpty(bdMaterials)) {
                bomSpecialmaterialMapper.insertBomSpecialmaterial(bdMaterial);
            } else {
                if (bdMaterials.size() != 1) {
                    for (int j = 1; j < bdMaterials.size(); j++) {
                        bomSpecialmaterialService.deleteBomSpecialmaterialById(bdMaterials.get(j).getId());
                    }
                }
                bdMaterial.setId(bdMaterials.get(0).getId());
                bdMaterial.setCreatetime(bdMaterials.get(0).getCreatetime());
                bdMaterial.setUpdatetime(new Date());
                bomSpecialmaterialService.updateBomSpecialmaterial(bdMaterial);
            }
            List<BomBaseunit> baseunits = bomBaseunitService.selectBomBaseunitList2(baseunit);
            if (StringUtils.isEmpty(baseunits)) {
                bomBaseunitService.insertBomBaseunit(baseunit);
            } else {
                if (baseunits.size() != 1) {
                    for (int j = 1; j < baseunits.size(); j++) {
                        bomBaseunitService.deleteBomBaseunitById(baseunits.get(j).getId());
                    }
                }
                baseunit.setId(baseunits.get(0).getId());
                bomBaseunitService.updateBomBaseunit(baseunit);
            }

        }
    }

    /**
     * 定时同步价格维护
     */
    public synchronized void SynPurprice() {
        JSONObject loginParam = loginParam();
        String access_token = (String) loginParam.get("access_token");
        String token_type = (String) loginParam.get("token_type");
        String s1 = "";
        SysConfig sysConfig = sysConfigService.selectConfigByConfigKey("purpriceUrl");
        Date successData = omsBaseDataTaskUtilMapper.getSuccessData("BomBaseDataTask.SynPurprice");
        //判断该定时任务之前是否存在成功的调度日志，有的话获取时间
        if (!StringUtils.isNull(successData)) {
            //增量获取
            String format = new SimpleDateFormat("yyyy-MM-dd").format(successData);
            s1 = HubUtil.doGetWithJson(
                    sysConfig.getConfigValue() + sysConfig.getRemark() + "'" + format + "'"
                    , token_type, access_token);
        } else {
            //全量获取
            s1 = HubUtil.doPostWithJson(sysConfig.getConfigValue(), token_type, access_token);
        }
        logger.info("--------------增量同步价格维护时，获取的数据：" + s1);
        System.out.println("--------------增量同步价格维护时，获取的数据：" + s1);
        if (StringUtils.isBlank(s1)) {
            return;
        }
        Date date = new Date();
        JSONObject jsonObject = JSON.parseObject(s1);
        JSONArray data = jsonObject.getJSONArray("data");
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObject1 = data.getJSONObject(i);
            BomRawmaterial bdPurprice = new BomRawmaterial();
            bdPurprice.setMaterialnumber(jsonObject1.getString("materialNumber"));
            bdPurprice.setMaterialname(jsonObject1.getString("materialName"));
            bdPurprice.setUnitnumber(jsonObject1.getString("baseUnitNumber"));
            bdPurprice.setUnitname(jsonObject1.getString("baseUnitName"));
            bdPurprice.setPrice(jsonObject1.getBigDecimal("price"));
            bdPurprice.setIstaxprice(jsonObject1.getString("isTaxPrice"));
            bdPurprice.setTaxrate(jsonObject1.getBigDecimal("taxRate"));
            bdPurprice.setEffectivedate(jsonObject1.getDate("effectiveDate"));
            bdPurprice.setExpiredate(jsonObject1.getDate("expireDate"));
            bdPurprice.setStopdate(jsonObject1.getDate("WRITE_DATE"));
            bdPurprice.setStatus("0");
            BomRawmaterial tempPurprice = new BomRawmaterial();
            tempPurprice.setMaterialnumber(jsonObject1.getString("materialNumber"));
            tempPurprice.setStatus("0");
            List<BomRawmaterial> tempPurprices = bomRawmaterialService.selectBomRawmaterialList2(tempPurprice);
            if (StringUtils.isEmpty(tempPurprices)) {
                bomRawmaterialService.insertBomRawmaterial(bdPurprice);
            } else {
                if (tempPurprices.size() != 1) {
                    for (int j = 1; j < tempPurprices.size(); j++) {
                        BomRawmaterial bomRawmaterial = tempPurprices.get(j);
                        if (bomRawmaterial.getExpiredate().getTime() - bdPurprice.getExpiredate().getTime() <= 0) {
                            bomRawmaterialService.deleteBomRawmaterialById(bomRawmaterial.getId());
                        }
                    }
                }
                BomRawmaterial bomRawmaterial = tempPurprices.get(0);
                bdPurprice.setId(bomRawmaterial.getId());
                bdPurprice.setKingdeeid(bomRawmaterial.getKingdeeid());
                long time = bdPurprice.getExpiredate().getTime();
                long time1 = bomRawmaterial.getExpiredate().getTime();
                if (time > time1) {
                    bomRawmaterialService.updateBomRawmaterial(bdPurprice);
                }
            }
        }
        updatePurpriceGroup();
    }
    /**
     * 更新分类编码
     */
    public synchronized void updatePurpriceGroup(){
        List<BomRawmaterial> bomRawmaterials = bomRawmaterialMapper.selectBomRawmaterialList3(null);
        for (int i = 0; i < bomRawmaterials.size(); i++) {
            BomRawmaterial bomRawmaterial = bomRawmaterials.get(i);
            String kingdeeid = bomRawmaterial.getKingdeeid();
            if (StringUtils.isEmpty(kingdeeid)){
                BomSpecialmaterial bomSpecialmaterial = new BomSpecialmaterial();
                bomSpecialmaterial.setMaterialnumber(bomRawmaterial.getMaterialnumber());
                List<BomSpecialmaterial> bomSpecialmaterials = bomSpecialmaterialService.selectBomSpecialmaterialList2(bomSpecialmaterial);
                if(bomSpecialmaterials!=null&&bomSpecialmaterials.size()!=0){
                    bomRawmaterial.setKingdeeid(bomSpecialmaterials.get(0).getGroup1name());
                    bomRawmaterialMapper.updateBomRawmaterial(bomRawmaterial);
                }
            }
        }
    }

    /**
     * 同步所有客户
     */
    public synchronized void SynAllCustomer() {
        JSONObject loginParam = loginParam();
        String access_token = (String) loginParam.get("access_token");
        String token_type = (String) loginParam.get("token_type");
        SysConfig sysConfig = sysConfigService.selectConfigByConfigKey("customerUrl");
        String s1 = HubUtil.doPostWithJson(sysConfig.getConfigValue(), token_type, access_token);
        logger.info("--------------全量同步客户时，获取的数据：" + s1);
        if (StringUtils.isBlank(s1)) {
            return;
        }
        JSONObject jsonObject = JSON.parseObject(s1);
        JSONArray data = jsonObject.getJSONArray("data");
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObject1 = data.getJSONObject(i);
            BomCustomer bdCustomer = new BomCustomer();
            bdCustomer.setCustomernumber(jsonObject1.getString("customernumber"));
            bdCustomer.setCustomername(jsonObject1.getString("customername"));
            bdCustomer.setGroupnumber(jsonObject1.getString("groupnumber"));
            bdCustomer.setGroupname(jsonObject1.getString("groupname"));
            bdCustomer.setIsinternal("true".equals(jsonObject1.getString("isinternal")) ? 1L : 0L);
            bdCustomer.setInternalcompanynumber(jsonObject1.getString("internalcompanynumber"));
            bdCustomer.setInternalcompanyname(jsonObject1.getString("internalcompanyname"));
            bdCustomer.setIscostcenter("true".equals(jsonObject1.getString("iscostcenter")) ? 1L : 0L);
            bdCustomer.setCostcenternumber(jsonObject1.getString("costcenternumber"));
            bdCustomer.setCostcentername(jsonObject1.getString("costcentername"));
            bdCustomer.setSaleorgnumber("0");
            bdCustomer.setSaleorgname(jsonObject1.getString("saleorgname"));
            bdCustomer.setAccountcompanynumber(jsonObject1.getString("accountcompanynumber"));
            bdCustomer.setAccountcompanyname(jsonObject1.getString("accountcompanyname"));
            bdCustomer.setStorewhnumber(jsonObject1.getString("storewhnumber"));
            bdCustomer.setStorewhname(jsonObject1.getString("storewhname"));
            bdCustomer.setVouchertypenumber(jsonObject1.getString("vouchertypenumber"));
            bdCustomer.setVouchertypename(jsonObject1.getString("vouchertypename"));
            BomCustomer tempCustomer = new BomCustomer();
            tempCustomer.setCustomernumber(bdCustomer.getCustomernumber());
            List<BomCustomer> tempCustomers = bomCustomerService.selectBomCustomerList2(tempCustomer);
            if (StringUtils.isEmpty(tempCustomers)) {
                bomCustomerService.insertBomCustomer(bdCustomer);
            } else {
                if (tempCustomers.size() != 1) {
                    for (int j = 1; j < tempCustomers.size(); j++) {
                        bomCustomerService.deleteBomCustomerById(tempCustomers.get(j).getId());
                    }
                }
                bdCustomer.setId(tempCustomers.get(0).getId());
                bomCustomerService.updateBomCustomer(bdCustomer);
            }

        }
    }

    /**
     * 定时同步成本中心
     */
    public synchronized void getEasCostCenter() {
        JSONObject loginParam = loginEas();
        String access_token = (String) loginParam.get("access_token");
        String token_type = (String) loginParam.get("token_type");
        String expires_in = loginParam.get("expires_in").toString();
        SysConfig sysConfig = sysConfigService.selectConfigByConfigKey("queryCostCenter");
        String queryCostCenter = HubUtil.doGetWithJson(sysConfig.getConfigValue(), token_type, access_token);
        logger.info("--------------同步成本中心时，获取的数据：" + queryCostCenter);
        if (StringUtils.isBlank(queryCostCenter)) {
            return;
        }
        JSONObject jsonObject = JSON.parseObject(queryCostCenter);
        if (jsonObject!=null&&jsonObject.containsKey("count")&&jsonObject.getInteger("count").compareTo(1)>0) {
            System.out.println("--------------金蝶数据获取状态：true");
            JSONArray data = jsonObject.getJSONArray("financialOrgs");
            List<BomCostcenter> bomCostcenters1 = bomCostcenterService.selectBomCostcenterList(null);
            String ids[] = new String[bomCostcenters1.size()];
            for (int i = 0; i < bomCostcenters1.size(); i++) {
                ids[i] = bomCostcenters1.get(i).getId();
            }
            if(ids!=null&&ids.length>0){
                bomCostcenterService.deleteBomCostcenterByIds(ids);
            }
            HashMap<String,ArrayList<BomCostcenter>> hashMap = new HashMap();
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObject1 = data.getJSONObject(i);
                BomCostcenter bomCostcenter = new BomCostcenter();
                if (jsonObject1.containsKey("is_cost_center")) {
                    if(!"1".equals(jsonObject1.getString("is_cost_center"))){
                        continue;
                    }
                }
                if (jsonObject1.containsKey("is_entity")) {
                    Boolean is_entity = jsonObject1.getBoolean("is_entity");
                    bomCostcenter.setIsbizunit(is_entity!=null&&is_entity ?"1":"0");
                }
                if (jsonObject1.containsKey("org_type")) {
                    bomCostcenter.setCosttype(jsonObject1.getString("org_type"));
                }
                if (jsonObject1.containsKey("state")) {
                    bomCostcenter.setIssealup(jsonObject1.getString("state"));
                }
                if (jsonObject1.containsKey("org_name")) {
                    bomCostcenter.setName(jsonObject1.getString("org_name"));
                }
                if (jsonObject1.containsKey("org_code")) {
                    bomCostcenter.setNumber(jsonObject1.getString("org_code"));
                }
                if (jsonObject1.containsKey("parent_org_code")) {
                    bomCostcenter.setParentnumber(jsonObject1.getString("parent_org_code"));
                }else{
                    bomCostcenter.setParentnumber("");
                }
                if (jsonObject1.containsKey("parent_org_name")) {
                    bomCostcenter.setParentname(jsonObject1.getString("parent_org_name"));
                }else{
                    bomCostcenter.setParentname("");
                }
                if (jsonObject1.containsKey("comNumber")) {
                    bomCostcenter.setComnumber(jsonObject1.getString("comNumber"));
                }
                if (jsonObject1.containsKey("comName")) {
                    bomCostcenter.setComname(jsonObject1.getString("comName"));
                }
                if (jsonObject1.containsKey("org_level")) {
                    String org_level = jsonObject1.getString("org_level");
                    if(hashMap.containsKey(org_level)){
                        ArrayList<BomCostcenter> bomCostcenters = hashMap.get(org_level);
                        bomCostcenters.add(bomCostcenter);
                        hashMap.put(org_level,bomCostcenters);
                    }else{
                        ArrayList<BomCostcenter> bomCostcenters = new ArrayList<>();
                        bomCostcenters.add(bomCostcenter);
                        hashMap.put(org_level,bomCostcenters);
                    }
                }
                bomCostcenterService.insertBomCostcenter(bomCostcenter);
            }
            Set<String> strings = hashMap.keySet();
            TreeSet<String> strings1 = new TreeSet<String>(strings);
            sysDeptServiceImpl.updateDeptByTask();
            for (String key : strings1) {
                if(key.equals("1")){
                    continue;
                }
                ArrayList<BomCostcenter> bomCostcenters = hashMap.get(key);
                for (int i = 0; bomCostcenters!=null&&i < bomCostcenters.size(); i++) {
                    BomCostcenter bomCostcenter = bomCostcenters.get(i);
                    SysDept sysDept = new SysDept();
                    String name = bomCostcenter.getName();
                    String number = bomCostcenter.getNumber();
                    sysDept.setDeptNumber(number);
                    BomCostcenter bomCostcenter1 = new BomCostcenter();
                    bomCostcenter1.setNumber(number);
                    bomCostcenter1.setName(name);
                    List<BomCostcenter> bomCostcenters2 = bomCostcenterMapper.selectBomCostcenterList2(bomCostcenter1);
                    if(bomCostcenters2!=null&&bomCostcenters2.size()==1){
                        List<SysDept> sysDepts = sysDeptServiceImpl.selectDeptList2(sysDept);
                        if(sysDepts==null||sysDepts.size()==0){
                            String parentnumber = bomCostcenters2.get(0).getParentnumber();
                            String parentname = bomCostcenters2.get(0).getParentname();
                            if(StringUtils.isNotBlank(parentname)){
                                SysDept sysDept1 = new SysDept();
                                sysDept1.setDeptName(parentname);
                                sysDept1.setDeptNumber(parentnumber);
                                List<SysDept> sysDepts1 = sysDeptServiceImpl.selectDeptList2(sysDept1);
                                if(sysDepts1!=null&&sysDepts1.size()==1){
                                    sysDept.setDeptName(name);
                                    sysDept.setParentId(sysDepts1.get(0).getDeptId());
                                    sysDept.setCreateBy("定时任务");
                                    sysDeptServiceImpl.insertDept(sysDept);
                                }
                            }
                        }
                        // 更新
                        else if(sysDepts!=null&&sysDepts.size()==1){
                            String parentnumber = bomCostcenters2.get(0).getParentnumber();
                            String parentname = bomCostcenters2.get(0).getParentname();
                            if(StringUtils.isNotBlank(parentname)){
                                SysDept sysDept1 = new SysDept();
                                sysDept1.setDeptName(parentname);
                                sysDept1.setDeptNumber(parentnumber);
                                List<SysDept> sysDepts1 = sysDeptServiceImpl.selectDeptList2(sysDept1);
                                if(sysDepts1!=null&&sysDepts1.size()==1){
                                    sysDept = sysDepts.get(0);
                                    sysDept.setDeptName(name);
                                    sysDept.setStatus("0");
                                    SysDept sysDept2 = sysDepts1.get(0);
                                    if(sysDept2.getStatus().equals("1")){
                                        continue;
                                    }
                                    sysDept.setParentId(sysDept2.getDeptId());
                                    sysDeptServiceImpl.updateDept(sysDept);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 定时同步物料分类
     */
    public synchronized void getEasMaterialGroup() {
        JSONObject loginParam = loginEas();
        String access_token = (String) loginParam.get("access_token");
        String token_type = (String) loginParam.get("token_type");
        SysConfig sysConfig = sysConfigService.selectConfigByConfigKey("queryMaterialGroup");
        String queryCostCenter = HubUtil.doGetWithJson(sysConfig.getConfigValue(), token_type, access_token);
        logger.info("--------------同步物料分类时，获取的数据：" + queryCostCenter);
        if (StringUtils.isBlank(queryCostCenter)) {
            return;
        }
        JSONObject jsonObject = JSON.parseObject(queryCostCenter);
        if (jsonObject!=null&&jsonObject.containsKey("count")&&jsonObject.getInteger("count").compareTo(1)>0) {
            System.out.println("--------------金蝶数据获取状态：true");
            JSONArray data = jsonObject.getJSONArray("productTypes");
            List<BomMaterialgroup> bomMaterialgroups = bomMaterialgroupService.selectBomMaterialgroupList(null);
            String ids[] = new String[bomMaterialgroups.size()];
            for (int i = 0; i < bomMaterialgroups.size(); i++) {
                ids[i] = bomMaterialgroups.get(i).getId();
            }
            if(ids!=null&&ids.length>0){
                bomMaterialgroupService.deleteBomMaterialgroupByIds(ids);
            }
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObject1 = data.getJSONObject(i);
                BomMaterialgroup bomCostcenter = new BomMaterialgroup();
                if (jsonObject1.containsKey("standard")) {
                    String standard = jsonObject1.getString("standard");
                    if(standard==null||!standard.contains("基本分类")){
                        continue;
                    }
                }
                if (jsonObject1.containsKey("status")) {
                    String status = jsonObject1.getString("status");
                    if(status==null||!"approved".equals(status)){
                        continue;
                    }
                }
                if (jsonObject1.containsKey("product_type_name")) {
                    bomCostcenter.setName(jsonObject1.getString("product_type_name"));
                }
                if (jsonObject1.containsKey("product_type_code")) {
                    bomCostcenter.setNumber(jsonObject1.getString("product_type_code"));
                    if(jsonObject1.getString("product_type_code").contains(".")||jsonObject1.getString("product_type_code").substring(0,1).equals("0")){
                        continue;
                    }
                }
                if("99".equals(jsonObject1.getString("product_type_code"))){
                    continue;
                }
                if("7003".equals(jsonObject1.getString("product_type_code"))||"7003".equals(jsonObject1.getString("parent_type_code"))){
                    continue;
                }
                if("9999".equals(jsonObject1.getString("product_type_code"))){
                    continue;
                }
                if (jsonObject1.containsKey("parent_type_code")) {
                    bomCostcenter.setParentnumber(jsonObject1.getString("parent_type_code"));
                }
                if (jsonObject1.containsKey("parent_type_name")) {
                    bomCostcenter.setParentname(jsonObject1.getString("parent_type_name"));
                }
                bomMaterialgroupService.insertBomMaterialgroup(bomCostcenter);
            }
        }
    }

    /**
     * 定时同步bom
     */
    public synchronized void getEasMaterialBom() {
        JSONObject loginParam = loginEas();
        String access_token = (String) loginParam.get("access_token");
        SysConfig sysConfig = sysConfigService.selectConfigByConfigKey("queryBom");
        JSONObject jsonParam = new JSONObject();
        SysConfig sysConfig1 = sysConfigService.selectConfigByConfigKey("easBomPage");
        String configValue = sysConfig1.getConfigValue();
        jsonParam.put("pageSize", configValue);
        jsonParam.put("pageNo", 1);
        Date successData = omsBaseDataTaskUtilMapper.getSuccessData("BomBaseDataTask.getEasMaterialBom");
        //判断该定时任务之前是否存在成功的调度日志，有的话获取时间
        if (!StringUtils.isNull(successData)) {
            //增量获取
            String format = new SimpleDateFormat("yyyy-MM-dd").format(successData);
            jsonParam.put("lastUpDate", format);
        } else {
            jsonParam.put("lastUpDate", "2010-10-12");
        }
        logger.info("--------------同步物料BOM时，最后更新时间：" + jsonParam.getString("lastUpDate"));
        logger.info("--------------同步物料BOM时，请求条数：" + jsonParam.getString("pageSize"));
        logger.info("--------------同步物料BOM时，请求页数：" + jsonParam.getString("pageNo"));
        String queryCostCenter = HubUtil.doPostWithJson(sysConfig.getConfigValue(), jsonParam.toString(), access_token);
        logger.info("--------------同步物料BOM时，获取的数据：" + queryCostCenter);
        while (true) {
            JSONObject jsonObject = JSON.parseObject(queryCostCenter);
            if (jsonObject!=null&&"success".equals(jsonObject.getString("flag"))) {
                JSONArray data = jsonObject.getJSONArray("data");
                for (int i = 0; i < data.size(); i++) {
                    JSONObject jsonObject1 = data.getJSONObject(i);
                    BomMaterialhalf materialhalf = new BomMaterialhalf();
                    materialhalf.setCfverson("0");
                    BomAsscategory bomAsscategory = new BomAsscategory();
                    if (jsonObject1.containsKey("materialNumber")) {
                        materialhalf.setCfmaterialnumber(jsonObject1.getString("materialNumber"));
                        bomAsscategory.setMaterialbomnumber(jsonObject1.getString("materialNumber"));
                        List<BomAsscategory> bomAsscategories = bomAsscategoryService.selectBomAsscategoryList2(bomAsscategory);
                        if (bomAsscategories != null && bomAsscategories.size() != 0) {
                            bomAsscategory = null;
                        }
                    }
                    if (jsonObject1.containsKey("materialName")) {
                        materialhalf.setCfmaterialname(jsonObject1.getString("materialName"));
                        if (bomAsscategory != null) {
                            bomAsscategory.setMaterialbomname(jsonObject1.getString("materialName"));
                        }
                    }
                    if (jsonObject1.containsKey("unitName")) {
                        materialhalf.setCfmaterialunit(jsonObject1.getString("unitName"));
                    }
                    if (jsonObject1.containsKey("productQty")) {
                        materialhalf.setCfproductionquantity(jsonObject1.getBigDecimal("productQty"));
                    }
                    if (jsonObject1.containsKey("entries")) {
                        JSONArray entries = jsonObject1.getJSONArray("entries");
                        List<BomMaterialhalfentry> list = new ArrayList<>();
                        for (int i1 = 0; i1 < entries.size(); i1++) {
                            JSONObject jsonObject2 = entries.getJSONObject(i1);
                            BomMaterialhalfentry entry = new BomMaterialhalfentry();
                            if (jsonObject2.containsKey("materialName")) {
                                entry.setCfrawmaterialname(jsonObject2.getString("materialName"));
                            }
                            if (jsonObject2.containsKey("materialNumber")) {
                                entry.setCfrawmaterialnumbe(jsonObject2.getString("materialNumber"));
                            }
                            if (jsonObject2.containsKey("unitName")) {
                                entry.setCfrawmaterialunit(jsonObject2.getString("unitName"));
                            }
                            if (jsonObject2.containsKey("consumeFixQty")) {
                                entry.setCfconsumption(jsonObject2.getBigDecimal("consumeFixQty"));
                            }
                            list.add(entry);
                        }
                        materialhalf.setBomMaterialhalfentryList(list);
                    }
                    BomMaterialhalf temp = new BomMaterialhalf();
                    temp.setCfmaterialnumber(materialhalf.getCfmaterialnumber());
                    List<BomMaterialhalf> list = bomMaterialhalfService.selectBomMaterialhalfList2(temp);
                    if (StringUtils.isEmpty(list)) {
                        bomMaterialhalfService.insertBomMaterialhalf(materialhalf);
                    } else {
                        if (list.size() != 1) {
                            for (int j = 1; j < list.size(); j++) {
                                bomMaterialhalfService.deleteBomMaterialhalfByFid(list.get(j).getFid());
                            }
                        }
                        materialhalf.setFid(list.get(0).getFid());
                        bomMaterialhalfService.updateBomMaterialhalf(materialhalf);
                    }
                    if (bomAsscategory != null) {
                        bomAsscategoryService.insertBomAsscategory(bomAsscategory);
                    }
                }
            } else {
                break;
            }
            //jsonObject.put("totalPage",jsonObject.getInteger("pageNo"))
            if (jsonObject.getInteger("totalPage").compareTo(jsonObject.getInteger("pageNo")) == 0) {
                break;
            }
            jsonParam.put("pageNo", jsonObject.getInteger("pageNo") + 1);
            queryCostCenter = HubUtil.doPostWithJson(sysConfig.getConfigValue(), jsonParam.toString(), access_token);
        }
    }
}
